<template>
  <view class="permissions-container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 权限列表 -->
    <view v-else class="permissions-content">
      <!-- 说明横幅 -->
      <view class="info-banner">
        <text class="banner-icon">ℹ️</text>
        <view class="banner-content">
          <text class="banner-title">权限说明</text>
          <text class="banner-text">点击权限项可跳转到系统设置进行授权</text>
        </view>
      </view>

      <!-- 权限列表 -->
      <view class="permissions-list">
        <view 
          v-for="permission in permissions" 
          :key="permission.id"
          class="permission-item"
          @click="handlePermissionClick(permission)"
        >
          <!-- 权限图标 -->
          <view class="permission-icon-wrapper">
            <text class="permission-icon">{{ permission.icon }}</text>
          </view>

          <!-- 权限信息 -->
          <view class="permission-info">
            <view class="permission-header">
              <text class="permission-name">{{ permission.name }}</text>
              <text v-if="permission.required" class="required-badge">必需</text>
            </view>
            <text class="permission-description">{{ permission.description }}</text>
          </view>

          <!-- 权限状态指示器 -->
          <view class="permission-status">
            <view 
              class="status-indicator"
              :class="{ 'status-granted': permission.granted, 'status-denied': !permission.granted }"
            >
              <text class="status-dot"></text>
            </view>
            <text class="status-text">{{ permission.granted ? '已授权' : '未授权' }}</text>
          </view>

          <!-- 箭头 -->
          <text class="permission-arrow">></text>
        </view>
      </view>

      <!-- 底部提示 -->
      <view class="bottom-tip">
        <text class="tip-icon">💡</text>
        <text class="tip-text">绿色表示已授权，灰色表示未授权</text>
      </view>

      <!-- 刷新按钮 -->
      <view class="refresh-section">
        <button class="refresh-btn" @click="refreshPermissions">
          <text class="refresh-icon">🔄</text>
          <text class="refresh-text">刷新权限状态</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import PermissionService from '@/utils/permission-service.js';

export default {
  data() {
    return {
      isLoading: true,
      permissions: [],
      isRefreshing: false,
      lastRefreshTime: 0
    };
  },

  onLoad() {
    this.loadPermissions();
  },

  onShow() {
    // 从系统设置返回时刷新权限状态
    // 添加防抖：如果距离上次刷新不足1秒，则不刷新
    const now = Date.now();
    if (!this.isLoading && !this.isRefreshing && (now - this.lastRefreshTime > 1000)) {
      this.refreshPermissions();
    }
  },

  methods: {
    async loadPermissions() {
      this.isLoading = true;

      try {
        // 获取所有权限状态
        const permissions = await PermissionService.getAllPermissionsStatus();
        this.permissions = permissions;

        console.log('权限状态加载成功:', this.permissions);
      } catch (error) {
        console.error('加载权限状态失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        });
      } finally {
        this.isLoading = false;
      }
    },

    async refreshPermissions() {
      // 防止重复刷新
      if (this.isRefreshing) {
        return;
      }

      this.isRefreshing = true;
      this.lastRefreshTime = Date.now();

      // 清除权限缓存
      PermissionService.clearPermissionCache();

      // 显示加载提示
      uni.showLoading({
        title: '刷新中...',
        mask: true
      });

      try {
        // 重新加载权限状态
        const permissions = await PermissionService.getAllPermissionsStatus();
        this.permissions = permissions;

        uni.hideLoading();
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        });

        console.log('权限状态已刷新:', this.permissions);
      } catch (error) {
        uni.hideLoading();
        console.error('刷新权限状态失败:', error);
        uni.showToast({
          title: '刷新失败',
          icon: 'error'
        });
      } finally {
        this.isRefreshing = false;
      }
    },

    handlePermissionClick(permission) {
      console.log('点击权限:', permission);

      // 显示确认对话框
      uni.showModal({
        title: `${permission.name}权限`,
        content: `${permission.description}\n\n当前状态：${permission.granted ? '已授权' : '未授权'}\n\n是否前往系统设置进行授权？`,
        confirmText: '去设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 打开系统设置
            PermissionService.openSystemSettings(permission.id);

            // 提示用户
            setTimeout(() => {
              uni.showToast({
                title: '请在系统设置中授权',
                icon: 'none',
                duration: 3000
              });
            }, 500);
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.permissions-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 权限内容 */
.permissions-content {
  padding-bottom: 40rpx;
}

/* 说明横幅 */
.info-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.banner-icon {
  font-size: 40rpx;
  margin-right: 16rpx;
}

.banner-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.banner-title {
  font-size: 28rpx;
  font-weight: bold;
  color: white;
}

.banner-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}

/* 权限列表 */
.permissions-list {
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.permission-item:last-child {
  border-bottom: none;
}

.permission-item:active {
  background-color: #f8f9fa;
}

/* 权限图标 */
.permission-icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.permission-icon {
  font-size: 40rpx;
}

/* 权限信息 */
.permission-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.permission-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.permission-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #2d3436;
}

.required-badge {
  background: #ff6b6b;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.permission-description {
  font-size: 24rpx;
  color: #636e72;
  line-height: 1.5;
}

/* 权限状态 */
.permission-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  margin-right: 16rpx;
}

.status-indicator {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.status-indicator.status-granted {
  background: #d4edda;
  border: 3rpx solid #28a745;
}

.status-indicator.status-denied {
  background: #f8d7da;
  border: 3rpx solid #dc3545;
}

.status-dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  display: block;
}

.status-granted .status-dot {
  background: #28a745;
}

.status-denied .status-dot {
  background: #dc3545;
}

.status-text {
  font-size: 20rpx;
  color: #636e72;
}

/* 箭头 */
.permission-arrow {
  font-size: 24rpx;
  color: #b2bec3;
}

/* 底部提示 */
.bottom-tip {
  background: #fff3cd;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-top: 20rpx;
  display: flex;
  align-items: center;
}

.tip-icon {
  font-size: 28rpx;
  margin-right: 12rpx;
}

.tip-text {
  flex: 1;
  font-size: 24rpx;
  color: #856404;
}

/* 刷新按钮 */
.refresh-section {
  margin-top: 30rpx;
}

.refresh-btn {
  background: white;
  border: 2rpx solid #667eea;
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  transition: all 0.3s ease;
}

.refresh-btn:active {
  background: #f8f9fa;
  transform: scale(0.98);
}

.refresh-icon {
  font-size: 28rpx;
}

.refresh-text {
  font-size: 28rpx;
  color: #667eea;
  font-weight: 500;
}
</style>
